package cn.byapps.controller;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Set;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.multipart.MultipartFile;

import cn.byapps.core.utils.DecryptUtil;
import cn.byapps.core.utils.ServletDownloadUtil;
import cn.byapps.entity.UploadFile;
import cn.byapps.entity.User;
import cn.byapps.service.UserService;

@Controller
public class GenealogyWebController {

	@Resource
	private UserService userService;
	@Value("${upload}")
	private String upLoadPath;

	@RequestMapping(value = { "/", "" }, method = RequestMethod.GET)
	public String index() {
		return "sign";
	}

	// 登录
	@RequestMapping(value = { "sign" }, method = RequestMethod.GET)
	public String sign() {
		return "sign";
	}

	// 列表
	@RequestMapping(value = { "list" }, method = RequestMethod.GET)
	public String list() {
		return "list";
	}

	// 注册
	@RequestMapping(value = { "register" }, method = RequestMethod.GET)
	public String register() {
		return "register";
	}

	// 留言
	@RequestMapping(value = { "lyan" }, method = RequestMethod.GET)
	public String lyan() {
		return "lyan";
	}

	// 留言
	@RequestMapping(value = { "detail" }, method = RequestMethod.GET)
	public String detail() {
		return "detail";
	}

	// 搜索错误页面
	@RequestMapping(value = { "searchError" }, method = RequestMethod.GET)
	public String searchError() {
		return "searchError";
	}

	// 详情
	@RequestMapping(value = { "details" }, method = RequestMethod.GET)
	public String details() {
		return "details";
	}

	// 复制
	@RequestMapping(value = { "copytree" }, method = RequestMethod.GET)
	public String copytree(String token, String p, HttpSession session) {
		if (token != null && !token.equals("")) {
			User u = userService.get(token);
			if (u != null && u.getPwd().equals(DecryptUtil.MD5(u.getLoginName() + p))) {
				session.setAttribute("topId", token);
			} else {
				return "searchError";
			}
		}
		return "copytree";
	}

	// 留言
	@RequestMapping(value = { "index" }, method = RequestMethod.GET)
	public String main(String token, HttpSession session) {
		User u = (User) session.getAttribute("loginUser");
		if (u != null) {
			session.setAttribute("loginUser", u);
		}
		return "main";
	}

	@RequestMapping(value = { "tree" }, method = RequestMethod.GET)
	public String tree(String token, HttpSession session) {
		if (token != null && !token.equals(""))
			session.setAttribute("topId", token);
		return "tree";
	}

	@RequestMapping(value = "login", method = RequestMethod.POST)
	public String login(String name, String pwd, HttpSession session) {
		User u = userService.login(name, DecryptUtil.MD5(name + pwd));

		if (u != null) {
			//1.28 若妻子登录，则显示丈夫的族谱
			if (u.getCoupleId() != null && u.getSex() != null && u.getSex().equals("女")) {
				session.setAttribute("topId", u.getCoupleId());
			} else {
				session.setAttribute("topId", u.getId());
			}
			session.setAttribute("loginUser", u);
			return "redirect:index";
		} else {
			session.removeAttribute("topId");
			session.removeAttribute("loginUser");
			return "redirect:register";
		}

	}

	/**
	 * 用户注册 reg
	 */
	@RequestMapping(value = "reg", method = RequestMethod.POST)
	public String reg(User user, HttpSession session) {
		user.setPwd(DecryptUtil.MD5(user.getLoginName() + user.getPwd()));
		user = userService.save(user);
		return "redirect:sign";
	}

	@RequestMapping(value = "logout", method = RequestMethod.GET)
	public String logout(HttpSession session) {
		// System.out.println(session.getId());
		session.invalidate();
		return "redirect:/sign";
	}

	@RequestMapping(value = "user", method = RequestMethod.GET)
	public String detail(String token, Model model) {
		User user = userService.get(token);
		model.addAttribute("user_detail", user);
		Set<UploadFile> filelist = user.getFiles();
		model.addAttribute("filelist", filelist);
		return "user";
	}

	@RequestMapping(value = "uploadFile", method = RequestMethod.POST)
	public String uploadFile(String token, String name, String title, MultipartFile myfile, HttpServletRequest request)
			throws Exception {
		if (myfile.isEmpty()) {
			return "redirect:user?token=" + token;
		}
		User u = userService.get(token);
		userService.uploadFile(u, name, title, myfile);
		return "redirect:user?token=" + token;
	}

	@RequestMapping(value = "deleteFile", method = RequestMethod.GET)
	public String deleteFile(String id, String token, HttpServletRequest request) throws Exception {
		// UploadFile s = userService.getFile(id);
		userService.deleteFile(id);

		return "redirect:user?token=" + token;
	}

	@RequestMapping(value = "downloadFile", method = RequestMethod.GET)
	public void importStudentPage(String id, HttpServletResponse response, HttpServletRequest request)
			throws Exception {
		UploadFile s = userService.getFile(id);
		if (s == null) {
			return;
		}
		// 重置response对象中的缓冲区，该方法可以不写，但是你要保证response缓冲区没有其他数据，否则导出可能会出现问题，建议加上
		response.reset();
		// 构建子节输入流
		InputStream is = null;
		// 构建子节输出流
		OutputStream os = null;

		String path = null;
		if (upLoadPath == null || upLoadPath.equals("")) {
			path = request.getServletContext().getRealPath("/upload/");// 获取项目路径+upload目录
		} else {
			path = upLoadPath;
		}
		try {
			// 文件名外的双引号处理firefox的空格截断问题
			// 通知浏览器以下载方式打开文件
			response.setHeader("content-disposition", String.format("attachment; filename=\"%s\"",
					ServletDownloadUtil.downCodeFileName(request, s.getFileName())));
			response.setContentType("application/octet-stream");
			response.setCharacterEncoding("UTF-8");
			is = new FileInputStream(path + s.getFilePath());
			os = response.getOutputStream();
			byte[] b = new byte[8192];
			int len = 0;
			while ((len = is.read(b)) > 0) {
				os.write(b, 0, len);
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				if (is != null) {
					is.close();
				}
				if (os != null) {
					os.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

}
